const Job = require('../models/job');
const Alumni = require('../models/alumni');

class JobController {
  // 发布新岗位
  static async createJob(req, res) {
    try {
      const jobData = req.body;
      const jobId = await Job.create(jobData);
      
      // 更新校友招聘状态
      await Job.updateAlumniOpenings(jobData.company);
      
      // 检查是否有校友在该公司
      const alumni = await Alumni.getPublicAlumniByCompany(jobData.company);
      if (alumni.length > 0) {
        await Job.update(jobId, { hasAlumni: true });
      }

      res.status(201).json({
        success: true,
        message: '岗位发布成功',
        data: { id: jobId }
      });
    } catch (error) {
      res.status(500).json({
        success: false,
        message: '岗位发布失败',
        error: error.message
      });
    }
  }

  // 搜索岗位
  static async searchJobs(req, res) {
    try {
      const { keywords, skills, hasAlumni } = req.query;
      const jobs = await Job.search({ keywords, skills, hasAlumni });
      
      res.json({
        success: true,
        data: jobs
      });
    } catch (error) {
      res.status(500).json({
        success: false,
        message: '搜索失败',
        error: error.message
      });
    }
  }

  // 获取岗位详情
  static async getJobDetail(req, res) {
    try {
      const jobId = req.params.id;
      const job = await Job.getById(jobId);
      
      if (!job) {
        return res.status(404).json({
          success: false,
          message: '岗位不存在'
        });
      }

      // 如果有校友在职，获取校友信息
      let alumni = [];
      if (job.has_alumni) {
        alumni = await Alumni.getPublicAlumniByCompany(job.company);
      }

      res.json({
        success: true,
        data: {
          ...job,
          alumni
        }
      });
    } catch (error) {
      res.status(500).json({
        success: false,
        message: '获取岗位详情失败',
        error: error.message
      });
    }
  }

  // 更新岗位状态
  static async updateJobStatus(req, res) {
    try {
      const jobId = req.params.id;
      const { status } = req.body;
      
      const success = await Job.update(jobId, { status });
      
      if (!success) {
        return res.status(404).json({
          success: false,
          message: '岗位不存在'
        });
      }

      res.json({
        success: true,
        message: '岗位状态更新成功'
      });
    } catch (error) {
      res.status(500).json({
        success: false,
        message: '更新岗位状态失败',
        error: error.message
      });
    }
  }
}

module.exports = JobController;
